<?php
// 应用公共文件

use app\admin\controller\User;
use app\common\service\utils\RetCodeUtils;
use think\facade\Config;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\File;
use Overtrue\Pinyin\Pinyin;
use think\facade\Session;
use app\common\Model\ConfigModel;


/**
 * 获取userid
 * 
 * @return array
 */
 function getuser()
    {
        // 判断用户是否登录，可以根据具体的业务逻辑去判断
        $user= Session::get('user');     
        return  $user;
    }

/**
 * 成功返回

 * @param array  $data 数据
 * @param string $msg  提示
 * @param int    $code 返回码
 * 
 * @return json
 */
function success($data = [], $msg = RetCodeUtils::SUCCESS_MSG, $code = RetCodeUtils::SUCCESS)
{
    
    $res['status'] = 1;
    $res['info']  = $data;
    $res['msg'] = $msg;

    print_r( json_encode($res, JSON_UNESCAPED_UNICODE));
}

/**
 * 错误返回
 * 
 * @param array  $data 数据
 * @param string $msg  提示
 * @param int    $code 返回码
 * 
 * @return json
 */
function error($data = [],$msg = RetCodeUtils::ERROR_MSG, $code = RetCodeUtils::ERROR)
{
    
    $res['status'] = 0;
    $res['info']  = $data;
    $res['msg'] = $msg;

    print_r( json_encode($res, JSON_UNESCAPED_UNICODE));die;
}

/**
 * 错误返回（抛出异常）
 *
 * @param string $msg  提示
 * @param int    $code 返回码
 * 
 * @return Exception
 */
function exception($msg = RetCodeUtils::ERROR_MSG, $code = RetCodeUtils::ERROR)
{
    throw new \think\Exception($msg, $code);
}

/**
 * 获取当前日期时间
 * 
 * @param string $format 格式，默认Y-m-d H:i:s
 *
 * @return string
 */
function datetime($format = 'Y-m-d H:i:s')
{
    return date($format);
}

/**
 * 时间戳 转成库龄格式
 * 
 * @param string $format 格式，默认Y-m-d H:i:s
 *
 * @return string
 */
function diffDate($date1,$date2)
{
    $datetime1 = new \DateTime(date('Y-m-d',$date1));
    $datetime2 = new \DateTime(date('Y-m-d',$date2));
    $interval = $datetime1->diff($datetime2);
    $time['y']         = $interval->format('%Y'); // 两个时间相差总年数
    $time['m']         = $interval->format('%m'); // 两个时间相差总月数
    $time['d']         = $interval->format('%d');// 两个时间相差总天数
    $time['h']         = $interval->format('%H');
    $time['i']         = $interval->format('%i');
    $time['s']         = $interval->format('%s');
    $time['a']         = $interval->format('%a');    // 两个时间相差总天数
    return $time['y'].'年'.$time['m'].'月'.$time['d'].'天';
}
/**
 *导出expcel
 * 
 * @param string $format 格式，默认Y-m-d H:i:s
 *
 * @return string
 */
function ExportExcel($data,$field,$title,$width){
       // 创建 Spreadsheet 对象
       $spreadsheet = new Spreadsheet();
       $sheet = $spreadsheet->getActiveSheet();
       // 设置表头
       $sheet->setTitle($title);
   
       foreach($data as $key => $value){
        foreach($field as $k => $v){
            if($key == 0){
                $sheet->setCellValue($k . '1', $v[1]);
            }
            $i = $key + 2; //表格是从2开始的
          
           $sheet->setCellValue($k . $i, $value[$v[0]]);
          
        }
    }
    //设置单元格宽度
    if($width){
        foreach($width as $key=>$value){
            $sheet->getColumnDimension($key)->setWidth($value);         
        }
    }
    // 设置文件名
    $filename = $title . date('YmdHis') . '.xlsx';
    // 直接输出到浏览器
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $filename . '"');
    header('Cache-Control: max-age=0');
    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');
    exit;
                 //  $param = request()->get();     
                 //  $data= StroagesService::inventorylog_export($param);  

}

/**
 *导出expcel
 * 
 * @param string $format 格式，默认Y-m-d H:i:s
 *
 * @return string
 */
function ImportExcel($file){ 
        // 存储目录（默认在 public/ 下）
        $savePath = 'uploads/excel/';
        if (!$file) {
            return error('未上传文件');die;
        }
        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true); // 自动创建目录
        }      

        try {
            $fileName = uniqid() . '.' . $file->extension();
            $file->move($savePath, $fileName);
            $spreadsheet = IOFactory::load($savePath . $fileName);
            $sheet = $spreadsheet->getActiveSheet();
            $data = $sheet->toArray();
        } catch (\Exception $e) {
          return error('上传失败：'. $e->getMessage());
        }
        $path=$savePath . $fileName;
        //删除文件
        unlink($path);
        return $data;
} 



    /**
 * 递归方法 菜单树形获取 
 */
function buildTree(array $data, $parentId = 0) {
    $branch = array();  
        if($data){
        foreach ($data as $item) {
            if ($item['pid'] == $parentId) {             
                $children = buildTree($data, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $branch[] = $item;
            }
        }
        }
    return $branch;
    }

       /**
     * 递归方法 获取所有上级    
     */
 function getAllparentIds($Model,$parentId) {      
        // 使用where方法来筛选父级ID

        $parent =$Model->whereIn('id', $parentId)->select()->toArray(); 
       
        // 初始化上级数组
        $parentarr = [];       
        if($parent){
            $parentarr= $parent;
              // 递归获取所有上级
            foreach ($parent as $paren) {
                if($paren['pid']!=0){             
                    $parentarr = array_merge($parentarr, getAllChildrenIds($Model,$paren['pid']));
                } 
            }
        } 
        return $parentarr;
    }

      /**
     * 递归方法 获取所有子级ID
     * @param $parentId 菜单父级ID
     * @return array
     */
     function getAllChildrenIds($Model,$parentId) {
      // 使用where方法来筛选父级ID
    $children =$Model->where(array('pid' => $parentId))->select();
    
    // 初始化子级ID数组
    $childrenIds = [];
    foreach ($children as $child) {
        $childrenIds[] = $child['id'];
    }
    
    // 递归获取所有子级ID
    foreach ($children as $child) {
        $childrenIds = array_merge($childrenIds, getAllChildrenIds($Model,$child['id']));
    }
    
    return $childrenIds;
}

if (!function_exists('get_first_letter')) {
    /**
     * 获取中文字符串的首字母
     * @param string $chinese 中文字符串
     * @param bool $onlyFirstChar 是否只返回第一个字的首字母
     * @return string
     */
    function get_first_letter(string $chinese, bool $onlyFirstChar = false): string
    {
        $pinyin = new Pinyin();
        
        // 获取所有字的首字母（返回数组，如 ['N', 'H', 'S', 'J']）
        $letters = $pinyin->abbr($chinese);
        
        if ($onlyFirstChar) {
            return $letters[0] ?? ''; // 只返回第一个字的首字母
        }
       
        return implode('', $letters->toArray()); // 拼接成字符串，如 "NHSJ"
    }

            /**
     * 处理数据特定的结构
     * @param array $param 前台传过来的参数  
     * @return array
     */   

     function skusGroupMerge(array $categories): array
    {
        $result = [];
        
        foreach ($categories as $category) {
            $newCategory = [
                'value' => $category['id'],
                'label' => $category['title']
            ];
            
            // 如果有子分类，递归处理
            if (!empty($category['children'])) {
                $newCategory['children'] = skusGroupMerge($category['children']);
            }
            
            $result[] = $newCategory;
        }
        
        return $result;
    }
     

     /**
     *图片上传
     * @param array $file 图片路径
     * @param array $savePath 存储路劲
     * @return array
     */   
     function upload($savePath,$file)
    {   
      
        // 保存到服务器
        // 存储目录（默认在 public/ 下）
        if(empty($savePath)){
            $savePath = 'uploads/images/';
        }else{
            $savePath = 'uploads/'.$savePath.'/';
        }

        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true); // 自动创建目录
        }
      
        $fileName = uniqid() . '.' . $file->extension(); // 生成随机文件名（如：5f3e7d8c9b2a1.jpg）
     
        try {
            $file->move($savePath, $fileName);
            $path='/'.$savePath . $fileName;
           return $path;
             
        } catch (\Exception $e) {
            return error('上传失败：'. $e->getMessage());
        }
    }
/****************************************************URL********************************************************************/
    //截断函数
    function get_sub_content($str, $start, $end){
        if ( $start == '' || $end == '' ){

            return;
        }
        $str = explode($start, $str);
        $str = explode($end, $str[1]);
        if(strpos($str[0], 'offer-type') !== false && strlen($str[1])>20){
            $strs=$str[1];
        }elseif(strpos($str[0], 'offer-type') == false ){
            $strs=$str[0];
        }    
        return  $strs;
    }
    /**
 * 使用curl获取远程数据
 * @param  string $url url连接
 * @return string      获取到的数据
 */
    function curl_get_contents($url, $post = 0, $postFields = '', $timeOut = 5, $header=array() ,$ssl = 0){
        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
        curl_setopt($ch, CURLOPT_ENCODING, "");
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,$ssl);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,$ssl);

        if($post && $postFields)
        {
            curl_setopt($ch,CURLOPT_POST,TRUE);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$postFields);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);               //是否显示头部信息
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);               //设置超时

        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']);        //设置 referer

        //curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);          //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
        $r=curl_exec($ch);
        curl_close($ch);
        return $r;
    }

    /**
     * crul post请求
     */
    function curl_post($url, $postData){
        // 1. 初始化 cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true); // POST 请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); // 数据编码
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应数据（不直接输出）
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 HTTPS 证书验证（生产环境需改为 true）

        // 2. 执行请求并获取返回数据
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            die('cURL 请求失败: ' . curl_error($ch));
        }
        curl_close($ch);
        // 3. 处理 B 网站的返回数据（假设是 JSON）
        $result = json_decode($response, true);
        return $result;     
    }

/****************************************************URL END********************************************************************/

    /**
 * 有道英文翻译的
 * @param  string $url url连接
 * @return string      获取到的数据 */
/******************************有道翻译****************************************** */
 function do_call($url, $method, $header, $param, $expectContentType, $timeout = 3000)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 不验证对等证书
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    $data = http_build_query($param);
    if ($method == 'post') {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    } else if ($method == 'get') {
        $url = $url . '?' . $data;
    } else {
        print 'http method not support';
        return null;
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    $r = curl_exec($curl);
    $contentType = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
    // if (strpos($contentType, $expectContentType) === false) {
    //     echo $r;
    //     $r = null;
    // }
    curl_close($curl);

    return $r;
}
function add_auth_params($param, $appKey, $appSecret)
{
    if (array_key_exists('q', $param)) {
        $q = $param['q'];
    } else {
        $q = $param['img'];
    }
    $salt = create_uuid();
    $curtime = strtotime("now");
    $sign = calculate_sign($appKey, $appSecret, $q, $salt, $curtime);
    $param['appKey'] = $appKey;
    $param['salt'] = $salt;
    $param["curtime"] = $curtime;
    $param['signType'] = 'v3';
    $param['sign'] = $sign;
    return $param;
}

function create_uuid()
{
    $str = md5(uniqid(mt_rand(), true));
    $uuid = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $uuid;
}

function calculate_sign($appKey, $appSecret, $q, $salt, $curtime)
{
    $strSrc = $appKey . get_input($q) . $salt . $curtime . $appSecret;
    return hash("sha256", $strSrc);
}

function get_input($q)
{
    if (empty($q)) {
        return null;
    }
    $len = mb_strlen($q, 'utf-8');
    return $len <= 20 ? $q : (mb_substr($q, 0, 10) . $len . mb_substr($q, $len - 10, $len));
}
/******************************有道翻译 end****************************************** */


   /**
     * 有道翻译
     * @param array $data 输入数组
     * @return array 处理后的数组
     */
    function translate($title, $lang = 'zh-CHS') {    
        
        $youdao=   (new ConfigModel())->getConfigist('youdao');                       
        $youdao = json_decode($youdao[0],true);                  
        $app_secret=$youdao['app_secret'];   
        $app_key=$youdao['app_key'];                  
        $q = $title;
        $from =$lang;
        $to = "en";   
        $params = array('q' => $q,
            'from' => $from,
            'to' => $to
            );
        $params = add_auth_params($params, $app_key,$app_secret);                           
        $r = do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
         $r = json_decode($r,true);    
        if(isset($r['translation'])){
            return $r['translation'][0];
        }else{
           error('翻译失败');
        }           
    }


    
}


